﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using PAT.Entities;
using PAT.Data;

#endregion

namespace PAT.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="PatDocumentoProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class PatDocumentoProviderBaseCore : EntityProviderBase<PAT.Entities.PatDocumento, PAT.Entities.PatDocumentoKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, PAT.Entities.PatDocumentoKey key)
		{
			return Delete(transactionManager, key.IdDocumento);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_idDocumento">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.Int32 _idDocumento)
		{
			return Delete(null, _idDocumento);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idDocumento">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.Int32 _idDocumento);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
	
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO Description: 
		/// </summary>
		/// <param name="_idTipoDocumento"></param>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		public TList<PatDocumento> GetByIdTipoDocumento(System.Int16 _idTipoDocumento)
		{
			int count = -1;
			return GetByIdTipoDocumento(_idTipoDocumento, 0,int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idTipoDocumento"></param>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		/// <remarks></remarks>
		public TList<PatDocumento> GetByIdTipoDocumento(TransactionManager transactionManager, System.Int16 _idTipoDocumento)
		{
			int count = -1;
			return GetByIdTipoDocumento(transactionManager, _idTipoDocumento, 0, int.MaxValue, out count);
		}
		
			/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idTipoDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		public TList<PatDocumento> GetByIdTipoDocumento(TransactionManager transactionManager, System.Int16 _idTipoDocumento, int start, int pageLength)
		{
			int count = -1;
			return GetByIdTipoDocumento(transactionManager, _idTipoDocumento, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		fkPatDocumentoPatTipoDocumento Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_idTipoDocumento"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		public TList<PatDocumento> GetByIdTipoDocumento(System.Int16 _idTipoDocumento, int start, int pageLength)
		{
			int count =  -1;
			return GetByIdTipoDocumento(null, _idTipoDocumento, start, pageLength,out count);	
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		fkPatDocumentoPatTipoDocumento Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_idTipoDocumento"></param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		public TList<PatDocumento> GetByIdTipoDocumento(System.Int16 _idTipoDocumento, int start, int pageLength,out int count)
		{
			return GetByIdTipoDocumento(null, _idTipoDocumento, start, pageLength, out count);	
		}
						
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO key.
		///		FK_PAT_DOCUMENTO_PAT_TIPO_DOCUMENTO Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idTipoDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns a typed collection of PAT.Entities.PatDocumento objects.</returns>
		public abstract TList<PatDocumento> GetByIdTipoDocumento(TransactionManager transactionManager, System.Int16 _idTipoDocumento, int start, int pageLength, out int count);
		
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override PAT.Entities.PatDocumento Get(TransactionManager transactionManager, PAT.Entities.PatDocumentoKey key, int start, int pageLength)
		{
			return GetByIdDocumento(transactionManager, key.IdDocumento, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="_idDocumento"></param>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public PAT.Entities.PatDocumento GetByIdDocumento(System.Int32 _idDocumento)
		{
			int count = -1;
			return GetByIdDocumento(null,_idDocumento, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="_idDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public PAT.Entities.PatDocumento GetByIdDocumento(System.Int32 _idDocumento, int start, int pageLength)
		{
			int count = -1;
			return GetByIdDocumento(null, _idDocumento, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idDocumento"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public PAT.Entities.PatDocumento GetByIdDocumento(TransactionManager transactionManager, System.Int32 _idDocumento)
		{
			int count = -1;
			return GetByIdDocumento(transactionManager, _idDocumento, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public PAT.Entities.PatDocumento GetByIdDocumento(TransactionManager transactionManager, System.Int32 _idDocumento, int start, int pageLength)
		{
			int count = -1;
			return GetByIdDocumento(transactionManager, _idDocumento, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="_idDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public PAT.Entities.PatDocumento GetByIdDocumento(System.Int32 _idDocumento, int start, int pageLength, out int count)
		{
			return GetByIdDocumento(null, _idDocumento, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_PAT_DOCUMENTO index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_idDocumento"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="PAT.Entities.PatDocumento"/> class.</returns>
		public abstract PAT.Entities.PatDocumento GetByIdDocumento(TransactionManager transactionManager, System.Int32 _idDocumento, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;PatDocumento&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;PatDocumento&gt;"/></returns>
		public static TList<PatDocumento> Fill(IDataReader reader, TList<PatDocumento> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				PAT.Entities.PatDocumento c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("PatDocumento")
					.Append("|").Append((System.Int32)reader[((int)PatDocumentoColumn.IdDocumento - 1)]).ToString();
					c = EntityManager.LocateOrCreate<PatDocumento>(
					key.ToString(), // EntityTrackingKey
					"PatDocumento",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new PAT.Entities.PatDocumento();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.IdDocumento = (System.Int32)reader[((int)PatDocumentoColumn.IdDocumento - 1)];
					c.DescripcionDocumento = (System.String)reader[((int)PatDocumentoColumn.DescripcionDocumento - 1)];
					c.IdTipoDocumento = (System.Int16)reader[((int)PatDocumentoColumn.IdTipoDocumento - 1)];
					c.NumeroIniicial = (System.Int32)reader[((int)PatDocumentoColumn.NumeroIniicial - 1)];
					c.NumeroFinal = (System.Int32)reader[((int)PatDocumentoColumn.NumeroFinal - 1)];
					c.UltimoConsecutivoUsado = (System.Int32)reader[((int)PatDocumentoColumn.UltimoConsecutivoUsado - 1)];
					c.Activo = (System.Boolean)reader[((int)PatDocumentoColumn.Activo - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="PAT.Entities.PatDocumento"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="PAT.Entities.PatDocumento"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, PAT.Entities.PatDocumento entity)
		{
			if (!reader.Read()) return;
			
			entity.IdDocumento = (System.Int32)reader[((int)PatDocumentoColumn.IdDocumento - 1)];
			entity.DescripcionDocumento = (System.String)reader[((int)PatDocumentoColumn.DescripcionDocumento - 1)];
			entity.IdTipoDocumento = (System.Int16)reader[((int)PatDocumentoColumn.IdTipoDocumento - 1)];
			entity.NumeroIniicial = (System.Int32)reader[((int)PatDocumentoColumn.NumeroIniicial - 1)];
			entity.NumeroFinal = (System.Int32)reader[((int)PatDocumentoColumn.NumeroFinal - 1)];
			entity.UltimoConsecutivoUsado = (System.Int32)reader[((int)PatDocumentoColumn.UltimoConsecutivoUsado - 1)];
			entity.Activo = (System.Boolean)reader[((int)PatDocumentoColumn.Activo - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="PAT.Entities.PatDocumento"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="PAT.Entities.PatDocumento"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, PAT.Entities.PatDocumento entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.IdDocumento = (System.Int32)dataRow["ID_DOCUMENTO"];
			entity.DescripcionDocumento = (System.String)dataRow["DESCRIPCION_DOCUMENTO"];
			entity.IdTipoDocumento = (System.Int16)dataRow["ID_TIPO_DOCUMENTO"];
			entity.NumeroIniicial = (System.Int32)dataRow["NUMERO_INIICIAL"];
			entity.NumeroFinal = (System.Int32)dataRow["NUMERO_FINAL"];
			entity.UltimoConsecutivoUsado = (System.Int32)dataRow["ULTIMO_CONSECUTIVO_USADO"];
			entity.Activo = (System.Boolean)dataRow["ACTIVO"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="PAT.Entities.PatDocumento"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">PAT.Entities.PatDocumento Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, PAT.Entities.PatDocumento entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;

			#region IdTipoDocumentoSource	
			if (CanDeepLoad(entity, "PatTipoDocumento|IdTipoDocumentoSource", deepLoadType, innerList) 
				&& entity.IdTipoDocumentoSource == null)
			{
				object[] pkItems = new object[1];
				pkItems[0] = entity.IdTipoDocumento;
				PatTipoDocumento tmpEntity = EntityManager.LocateEntity<PatTipoDocumento>(EntityLocator.ConstructKeyFromPkItems(typeof(PatTipoDocumento), pkItems), DataRepository.Provider.EnableEntityTracking);
				if (tmpEntity != null)
					entity.IdTipoDocumentoSource = tmpEntity;
				else
					entity.IdTipoDocumentoSource = DataRepository.PatTipoDocumentoProvider.GetByIdTipoDocumento(transactionManager, entity.IdTipoDocumento);		
				
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'IdTipoDocumentoSource' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.IdTipoDocumentoSource != null)
				{
					innerList.SkipChildren = true;
					DataRepository.PatTipoDocumentoProvider.DeepLoad(transactionManager, entity.IdTipoDocumentoSource, deep, deepLoadType, childTypes, innerList);
					innerList.SkipChildren = false;
				}
					
			}
			#endregion IdTipoDocumentoSource
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByIdDocumento methods when available
			
			#region PatTransferenciaCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<PatTransferencia>|PatTransferenciaCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'PatTransferenciaCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.PatTransferenciaCollection = DataRepository.PatTransferenciaProvider.GetByIdDocumento(transactionManager, entity.IdDocumento);

				if (deep && entity.PatTransferenciaCollection.Count > 0)
				{
					deepHandles.Add("PatTransferenciaCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<PatTransferencia>) DataRepository.PatTransferenciaProvider.DeepLoad,
						new object[] { transactionManager, entity.PatTransferenciaCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region PatOrdenTrabajoCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<PatOrdenTrabajo>|PatOrdenTrabajoCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'PatOrdenTrabajoCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.PatOrdenTrabajoCollection = DataRepository.PatOrdenTrabajoProvider.GetByIdDocumento(transactionManager, entity.IdDocumento);

				if (deep && entity.PatOrdenTrabajoCollection.Count > 0)
				{
					deepHandles.Add("PatOrdenTrabajoCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<PatOrdenTrabajo>) DataRepository.PatOrdenTrabajoProvider.DeepLoad,
						new object[] { transactionManager, entity.PatOrdenTrabajoCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the PAT.Entities.PatDocumento object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">PAT.Entities.PatDocumento instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">PAT.Entities.PatDocumento Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, PAT.Entities.PatDocumento entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			
			#region IdTipoDocumentoSource
			if (CanDeepSave(entity, "PatTipoDocumento|IdTipoDocumentoSource", deepSaveType, innerList) 
				&& entity.IdTipoDocumentoSource != null)
			{
				DataRepository.PatTipoDocumentoProvider.Save(transactionManager, entity.IdTipoDocumentoSource);
				entity.IdTipoDocumento = entity.IdTipoDocumentoSource.IdTipoDocumento;
			}
			#endregion 
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
	
			#region List<PatTransferencia>
				if (CanDeepSave(entity.PatTransferenciaCollection, "List<PatTransferencia>|PatTransferenciaCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(PatTransferencia child in entity.PatTransferenciaCollection)
					{
						if(child.IdDocumentoSource != null)
						{
							child.IdDocumento = child.IdDocumentoSource.IdDocumento;
						}
						else
						{
							child.IdDocumento = entity.IdDocumento;
						}

					}

					if (entity.PatTransferenciaCollection.Count > 0 || entity.PatTransferenciaCollection.DeletedItems.Count > 0)
					{
						//DataRepository.PatTransferenciaProvider.Save(transactionManager, entity.PatTransferenciaCollection);
						
						deepHandles.Add("PatTransferenciaCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< PatTransferencia >) DataRepository.PatTransferenciaProvider.DeepSave,
							new object[] { transactionManager, entity.PatTransferenciaCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
	
			#region List<PatOrdenTrabajo>
				if (CanDeepSave(entity.PatOrdenTrabajoCollection, "List<PatOrdenTrabajo>|PatOrdenTrabajoCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(PatOrdenTrabajo child in entity.PatOrdenTrabajoCollection)
					{
						if(child.IdDocumentoSource != null)
						{
							child.IdDocumento = child.IdDocumentoSource.IdDocumento;
						}
						else
						{
							child.IdDocumento = entity.IdDocumento;
						}

					}

					if (entity.PatOrdenTrabajoCollection.Count > 0 || entity.PatOrdenTrabajoCollection.DeletedItems.Count > 0)
					{
						//DataRepository.PatOrdenTrabajoProvider.Save(transactionManager, entity.PatOrdenTrabajoCollection);
						
						deepHandles.Add("PatOrdenTrabajoCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< PatOrdenTrabajo >) DataRepository.PatOrdenTrabajoProvider.DeepSave,
							new object[] { transactionManager, entity.PatOrdenTrabajoCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region PatDocumentoChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>PAT.Entities.PatDocumento</c>
	///</summary>
	public enum PatDocumentoChildEntityTypes
	{
		
		///<summary>
		/// Composite Property for <c>PatTipoDocumento</c> at IdTipoDocumentoSource
		///</summary>
		[ChildEntityType(typeof(PatTipoDocumento))]
		PatTipoDocumento,
	
		///<summary>
		/// Collection of <c>PatDocumento</c> as OneToMany for PatTransferenciaCollection
		///</summary>
		[ChildEntityType(typeof(TList<PatTransferencia>))]
		PatTransferenciaCollection,

		///<summary>
		/// Collection of <c>PatDocumento</c> as OneToMany for PatOrdenTrabajoCollection
		///</summary>
		[ChildEntityType(typeof(TList<PatOrdenTrabajo>))]
		PatOrdenTrabajoCollection,
	}
	
	#endregion PatDocumentoChildEntityTypes
	
	#region PatDocumentoFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;PatDocumentoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="PatDocumento"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PatDocumentoFilterBuilder : SqlFilterBuilder<PatDocumentoColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PatDocumentoFilterBuilder class.
		/// </summary>
		public PatDocumentoFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PatDocumentoFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PatDocumentoFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PatDocumentoFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PatDocumentoFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PatDocumentoFilterBuilder
	
	#region PatDocumentoParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;PatDocumentoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="PatDocumento"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PatDocumentoParameterBuilder : ParameterizedSqlFilterBuilder<PatDocumentoColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PatDocumentoParameterBuilder class.
		/// </summary>
		public PatDocumentoParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PatDocumentoParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PatDocumentoParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PatDocumentoParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PatDocumentoParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PatDocumentoParameterBuilder
	
	#region PatDocumentoSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;PatDocumentoColumn&gt;"/> class
	/// that is used exclusively with a <see cref="PatDocumento"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class PatDocumentoSortBuilder : SqlSortBuilder<PatDocumentoColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PatDocumentoSqlSortBuilder class.
		/// </summary>
		public PatDocumentoSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion PatDocumentoSortBuilder
	
} // end namespace
